package org.fone.pojo;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Table implements Serializable {
    private String tableName;
    private List<TableField> tableFields;
    private LinkedList<Map<String,Object>> tableLines;

    public Table(String tableName, List<TableField> tableFields, LinkedList<Map<String, Object>> tableLines) {
        this.tableName = tableName;
        this.tableFields = tableFields;
        this.tableLines = tableLines;
    }

    public boolean initDataType(){
        for (TableField field : tableFields) {
            if ("date".equals(field.getData_type())){
                for (Map<String, Object> line : tableLines){
                    Object obj = line.get(field.getColumn_name());
                    String objClassName = obj.getClass().getName();
                    objClassName=objClassName.substring(objClassName.lastIndexOf(".")+1);
                    System.out.println("objClassName = " + objClassName);

                    if ("Long".equals(objClassName)||"String".equals(objClassName)||"Integer".equals(objClassName))
                        line.put(field.getColumn_name(),new Timestamp(Long.parseLong(obj.toString())));
                    else if (!"TimeStamp".equals(objClassName)) return false;
                }
            }
        }
        return true;
    }
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public void setTableFields(List<TableField> tableFields) {
        this.tableFields = tableFields;
    }

    public void setTableLines(LinkedList<Map<String, Object>> tableLines) {
        this.tableLines = tableLines;
    }

    public String getTableName() {
        return tableName;
    }

    public List<TableField> getTableFields() {
        return tableFields;
    }

    public LinkedList<Map<String, Object>> getTableLines() {
        return tableLines;
    }

    @Override
    public Table clone() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            Table table = (Table) ois.readObject();
            ois.close();
            return table;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public String toString() {
        return "Table{" +
                "tableName='" + tableName + '\'' +
                ", tableFields=" + tableFields +
                ", tableLines=" + tableLines +
                '}';
    }
}
